import _thread
import os
import time
from threading import Thread


import requests
from loguru import logger
from PIL import Image
from io import BytesIO
import pickle

requests.packages.urllib3.disable_warnings()


class showpng(Thread):
    def __init__(self, data):
        Thread.__init__(self)
        self.data = data

    def run(self):
        img = Image.open(BytesIO(self.data))
        img.show()

class WechatLogin:

    def __init__(self):
        self.session = requests.session()
        logger.info(self.session.headers)
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36',
            'Referer': 'https://mp.weixin.qq.com/'
        }
        self.QRImgPath = os.path.split(os.path.realpath(__file__))[0] + os.sep + 'webWeixinQr.jpg'
        self.QRImgPath2 = os.path.split(os.path.realpath(__file__))[0] + os.sep + 'weixinQr.jpg'
        self.username = "mizhenwenwan@163.com"
        self.password = "sxun*@2012"
        self.token = ''

    # 直接扫码登录
    def get_weixin_qrcode(self):
        session = requests.session()
        session.get('https://mp.weixin.qq.com/', headers=self.headers)
        session.post('https://mp.weixin.qq.com/cgi-bin/bizlogin?action=startlogin',
                     data='userlang=zh_CN&redirect_url=&login_type=3&sessionid={}&token=&lang=zh_CN&f=json&ajax=1'.format(
                         int(time.time() * 1000)), headers=self.headers)
        loginurl = session.get('https://mp.weixin.qq.com/cgi-bin/scanloginqrcode?action=getqrcode&random={}'.format(
            int(time.time() * 1000)))

        dateurl = 'https://mp.weixin.qq.com/cgi-bin/scanloginqrcode?action=ask&token=&lang=zh_CN&f=json&ajax=1'
        t = showpng(loginurl.content)
        t.start()
        cookie_str = ""
        while 1:
            date = session.get(dateurl).json()
            if date['status'] == 0:
                print('二维码未失效，请扫码！')
            elif date['status'] == 6:
                print('已扫码，请确认！')
            if date['status'] == 1:
                print('已确认，登录成功！')
                url = session.post('https://mp.weixin.qq.com/cgi-bin/bizlogin?action=login',
                                   data='userlang=zh_CN&redirect_url=&cookie_forbidden=0&cookie_cleaned=1&plugin_used=0&login_type=3&token=&lang=zh_CN&f=json&ajax=1',
                                   headers=self.headers).json()
                # pprint(url)
                res = session.get('https://mp.weixin.qq.com{}'.format(url['redirect_url']), headers=self.headers)
                # pprint(res.cookies)
                cookiejar = res.cookies
                # pprint(cookiejar)
                cookies_dict = requests.utils.dict_from_cookiejar(cookiejar)

                key_value_pairs = [f"{k}={v}" for k, v in cookies_dict.items()]
                cookie_str = ";".join(key_value_pairs)
                red_url = url['redirect_url']
                token = red_url[red_url.rfind("=") + 1:len(red_url)]
                logger.info("cookie:{}".format(cookie_str))
                logger.info("token:{}".format(token))

                break
            time.sleep(2)

if __name__ == '__main__':
    wechat = WechatLogin()
    wechat.get_weixin_qrcode()

